<?php

/**
 * Some rights reserved：abc3210.com
 * Contact email:admin@abc3210.com
 */
define("SYS_TIME", time()); //时间
//网站所在目录，如果是根目录则是/
$Domain = urlDomain(CONFIG_SITEURL);
if ($Domain) {
    define("WEB_PATH", "/" . str_replace($Domain, "", CONFIG_SITEURL));
} else {
    define("WEB_PATH", "/");
}

class Url {

    private $urlrules, $categorys;

    function __construct() {
        //栏目缓存
        $this->categorys = F("Category");
        //获取URL生成规则缓存
        $this->urlrules = F("urlrules");
    }

    /**
     * 获取父栏目路径
     * @param  $catid 父栏目id
     */
    public function get_parentdir($catid) {
        if ($this->categorys[$catid]['parentid'] == 0)
            return '';
        $r = $this->categorys[$catid];
        if (empty($r)) {
            return "";
        }

        $setting = unserialize($r['setting']);
        $url = $r['url'];
        $arrparentid = $r['arrparentid'];
        unset($r);
        if (strpos($url, '://') === false) {
            $arrparentid = explode(',', $arrparentid);
            $arrcatdir = array();
            foreach ($arrparentid as $id) {
                if ($id == 0)
                    continue;
                $arrcatdir[] = $this->categorys[$id]['catdir'];
            }
            return implode('/', $arrcatdir) . '/';
        } else {
            $arrparentid = explode(',', $arrparentid);
            $arrcatdir = array();
            krsort($arrparentid);
            foreach ($arrparentid as $id) {
                if ($id == 0)
                    continue;
                $arrcatdir[] = $this->categorys[$id]['catdir'];
                if ($this->categorys[$id]['parentdir'] == '')
                    break;
            }
            krsort($arrcatdir);
            return implode('/', $arrcatdir) . '/';
        }
    }

    /**
     * 内容页链接
     * @param $id 内容id
     * @param $page 当前页
     * @param $catid 栏目id
     * @param $time 添加时间
     * @param $prefix 前缀
     * @param $data 数据
     * @param $action 操作方法
     * @param $upgrade 是否是升级数据
     * @return array 0=>url , 1=>生成路径
     */
    public function show($id, $page = 0, $catid = 0, $time = 0, $prefix = '', $data = '', $action = 'edit', $upgrade = 0) {
        $page = max($page, 1);
        $urls = $catdir = '';
        $category = $this->categorys[$catid];
        $setting = unserialize($category['setting']);
        //是否生成内容静态
        $content_ishtml = $setting['content_ishtml'];
        //内容规则ID
        $show_ruleid = $setting['show_ruleid'];
        //取得URL规则
        $urlrules = $this->urlrules[$show_ruleid];
        if (empty($urlrules)) {
            return false;
        }
        if (!$time)
            $time = SYS_TIME;
        $urlrules_arr = explode('|', $urlrules);
        //判断是否为第一页
        if ($page == 1) {
            $urlrule = $urlrules_arr[0];
        } else {
            $urlrule = isset($urlrules_arr[1]) ? $urlrules_arr[1] : $urlrules_arr[0];
        }
        $domain_dir = '';
        //判断栏目地址是绑定域名，如果绑定了域名，内容页会生成到绑定域名的栏目下面
        if (strpos($category['url'], '://') !== false && strpos($category['url'], '?') === false) {
            if (preg_match('/^((http|https):\/\/)?([^\/]+)/i', $category['url'], $matches)) {
                $match_url = $matches[0];
                $url = $match_url . '/';
            }
            $db = M("Category");
            $r['catid'] = $db->where(array('url' => $url))->getField('catid');
            //取得顶级绑定域名的栏目目录
            if ($r)
                $domain_dir = $this->get_categorydir($r['catid']) . $this->categorys[$r['catid']]['catdir'] . '/';
        }
        $categorydir = $this->get_categorydir($catid);
        $catdir = $category['catdir'];
        $year = date('Y', $time);
        $month = date('m', $time);
        $day = date('d', $time);

        //自定义文件名
        if ($content_ishtml && $prefix) {
            $Filename = trim($prefix);
        } else {
            $Filename = $id;
        }
        $urls = str_replace(array('{$categorydir}', '{$catdir}', '{$year}', '{$month}', '{$day}', '{$catid}', '{$id}', '{$page}'), array($categorydir, $catdir, $year, $month, $day, $catid, $Filename, $page), $urlrule);

        if ($content_ishtml && $url) {
            if ($domain_dir && $category['isdomain']) {
                $url_arr[1] = $html_root . '/' . $domain_dir . $urls;
                $url_arr[0] = $url . $urls;
            } else {
                $url_arr[1] = '/' . $urls;
                $url_arr[0] = WEB_PATH == '/' ? $match_url . '/' . $urls : $match_url . rtrim(WEB_PATH, '/') . '/' . $urls;
            }
        } elseif ($content_ishtml) {
            $url_arr[0] = WEB_PATH == '/' ? '/' . $urls : rtrim(WEB_PATH, '/') . '/' . $urls;
            $url_arr[1] = '/' . $urls;
        } else {
            $url_arr[0] = $url_arr[1] = CONFIG_SITEURL . $urls;
        }

        //生成静态 ,在添加文章的时候，同时生成静态，不在批量更新URL处调用
        if ($content_ishtml && $data) {
            $data['id'] = $id;
            $url_arr['content_ishtml'] = 1;
            $url_arr['data'] = $data;
        }
        return $url_arr;
    }

    /**
     * 获取栏目的访问路径
     * 在修复栏目路径处重建目录结构用
     * @param intval $catid 栏目ID
     * @param intval $page 页数
     */
    public function category_url($catid, $page = 1) {
        $category = $this->categorys[$catid];

        //外部链接直接返回外部地址
        if ($category['type'] == 2)
            return $category['url'];
        //页码
        $page = max(intval($page), 1);
        //栏目扩展配置信息反序列化
        $setting = unserialize($category['setting']);
        //栏目URL生成规则ID
        $category_ruleid = $setting['category_ruleid'];
        //取得规则
        $urlrules = $this->urlrules[$category_ruleid];
        //判断是URL规则缓存是否存在
        if (!$urlrules) {
            return false;
        }
        $urlrules_arr = explode('|', $urlrules);
        //判断是否首页
        if ($page == 1) {
            $urlrule = $urlrules_arr[0];
        } else {
            $urlrule = $urlrules_arr[1];
        }
        //检测是否要生成静态
        if (!$setting['ishtml']) { //如果不生成静态
            $url = str_replace(array('{$catid}', '{$page}'), array($catid, $page), $urlrule);
            if (strpos($url, '\\') !== false) {
                $url = CONFIG_SITEURL . str_replace('\\', '/', $url);
            }
        } else { //生成静态
            //所有父ID
            if ($category['arrparentid']) {
                $parentids = explode(',', $category['arrparentid']);
            }

            //把自身栏目id加入到父id数组中
            $parentids[] = $catid;
            $domain_dir = '';

            foreach ($parentids as $pid) { //循环查询父栏目是否设置了二级域名
                $r = $this->categorys[$pid];
                //判断url是不是带有://且不是动态地址，动态地址表示本站，绑定域名是不带?的
                if (strpos(strtolower($r['domain']), '://') !== false && strpos($r['domain'], '?') === false) {
                    $r['domain'] = preg_replace('/([(http|https):\/\/]{0,})([^\/]*)([\/]{1,})/i', '$1$2/', $r['domain'], -1); //取消掉双'/'情况
                    if (substr_count($r['domain'], '/') == 3 && substr($r['url'], -1, 1) == '/') { //如果url中包含‘http://’并且‘/’在3个则为二级域名设置栏目
                        $url = $r['url'];
                        //获取父栏目路径
                        $domain_dir = $this->get_categorydir($pid) . $this->categorys[$pid]['catdir'] . '/'; //得到二级域名的目录
                    }
                }
            }

            //获取当前栏目父栏目路径
            $category_dir = $this->get_categorydir($catid);

            $urls = str_replace(array('{$categorydir}', '{$catdir}', '{$catid}', '{$page}'), array($category_dir, $category['catdir'], $catid, $page), $urlrule);
            if ($url && $domain_dir) { //如果存在设置二级域名的情况
                if (strpos($urls, $domain_dir) === 0) {
                    $url = str_replace(array($domain_dir, '\\'), array($url, '/'), $urls);
                } else {
                    $urls = $domain_dir . $urls;
                    $url = str_replace(array($domain_dir, '\\'), array($url, '/'), $urls);
                }
            } else { //不存在二级域名的情况
                $url = $urls;
            }
        }

        //判断是否为首页文件，如果是，就不显示文件名，隐藏
        if (in_array(basename($url), array('index.html', 'index.htm', 'index.shtml'))) {
            $url = dirname($url) . '/';
        }
        if (strpos($url, '://') === false)
            $url = str_replace('//', '/', $url);
        if (strpos($url, '/') === 0)
            $url = substr($url, 1);
        return $url;
    }

    /**
     * 生成列表页分页地址
     * @param $ruleid 角色id
     * @param $categorydir 父栏目路径
     * @param $catdir 栏目路径
     * @param $catid 栏目id
     * @param $page 当前页
     */
    public function get_list_url($ruleid, $categorydir, $catdir, $catid, $page = 1) {
        $urlrules = $this->urlrules[$ruleid];
        $urlrules_arr = explode('|', $urlrules);
        if ($page == 1) {
            $urlrule = $urlrules_arr[0];
        } else {
            $urlrule = $urlrules_arr[1];
        }
        $urls = str_replace(array('{$categorydir}', '{$catdir}', '{$year}', '{$month}', '{$day}', '{$catid}', '{$page}'), array($categorydir, $catdir, $year, $month, $day, $catid, $page), $urlrule);
        return $urls;
    }

    /**
     * 获取父栏目路径
     * @param $catid
     * @param $dir
     */
    public function get_categorydir($catid, $dir = '') {
        $setting = array();
        $setting = unserialize($this->categorys[$catid]['setting']);
        if ($setting['create_to_html_root']) {
            return $dir;
        }
        if ($this->categorys[$catid]['parentid']) {
            $dir = $this->categorys[$this->categorys[$catid]['parentid']]['catdir'] . '/' . $dir;
            return $this->get_categorydir($this->categorys[$catid]['parentid'], $dir);
        } else {
            return $dir;
        }
    }

}

?>
